//
//  ZJMineThroughRecordViewController.m
//  ZJControlsClass
//
//  Created by wandoufo on 2024/12/7.
//

#import "ZJMineThroughRecordViewController.h"
#import "ZJMineThroughRecordInfoViewController.h"
#import "ZJMineThroughRecordInfoMoreView.h"

#import "ZJMineThroughRecordTableViewCell.h"
#import "ZJMineThroughRecordMoreDraw.h"
#import "MineNetWorking.h"
#import "ZJMineThroughRecordModel.h"

#import "SaTMNewUIPickerAlertView.h"
#import "SexAlertView.h"

#import "publicNodataView.h"



@interface ZJMineThroughRecordViewController () <UITableViewDelegate, UITableViewDataSource, ZJMineThroughRecordMoreDrawDelegate,protocolCanleMoreViewDelegate>
{
    NSInteger pageNo;
    NSInteger pageSize;
    
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

// 筛选视图
@property (nonatomic, strong) UIView *filterView;
@property (nonatomic, strong) UIButton *startTimeBtn;
@property (nonatomic, strong) UIButton *endTimeBtn; 
@property (nonatomic, strong) UIButton *typeBtn;
@property (nonatomic, strong) UIButton *moreBtn;


@property (nonatomic, strong) MineTrafficRecordListNetWorking * manager;
@property (nonatomic, strong) NSMutableDictionary * paramer;


@property (nonatomic,strong) SaTMNewUIPickerAlertView * checkPickerView;
@property (nonatomic,strong) SexAlertView * sexView;

@property (nonatomic,strong) UIView * kwinDowView;
@property (nonatomic,strong) ZJMineThroughRecordInfoMoreView * moreVoew;

@property (nonatomic,strong) publicNodataView * nodataView;


@end

@implementation ZJMineThroughRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通行记录";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.view.backgroundColor = [UIColor whiteColor];
    
    self.kwinDowView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.kwinDowView.backgroundColor = [UIColor blackColor];
    self.kwinDowView.alpha = 0;
    [kWindow addSubview:self.kwinDowView];
    
    self.moreVoew = [[ZJMineThroughRecordInfoMoreView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.moreVoew.delegate  = self;
    [kWindow addSubview:self.moreVoew];
    
    pageNo = 1;
    pageSize = 20;
    
    [self setupUI];
    [self loadNet];
}

-(void)loadNet{
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"正在加载...";
    [hud removeFromSuperViewOnHide];
    
    [self.paramer setValue:[NSString stringWithFormat:@"%@",@(pageNo)] forKey:@"pageNo"];
    [self.paramer setValue:[NSString stringWithFormat:@"%@",@(pageSize)] forKey:@"pageSize"];
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [self.paramer setValue:[NSString stringWithFormat:@"%@",[defaults valueForKey:@"userId"]] forKey:@"userId"];
    [self.manager dispatchTaskWithParam:self.paramer completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [hud hideAnimated:YES];
        
        if (responseObject && [responseObject[@"code"] intValue] == 200){
            
        if (self->pageNo == 1) {
            [self.dataArray removeAllObjects];
        }
        NSArray * data = responseObject[@"data"][@"list"];
            
            if (data.count == 0) {
                self.nodataView.hidden = NO;
            }else{
                self.nodataView.hidden = YES;
            }
            
        if (data.count < 20)[self.tableView.mj_footer endRefreshingWithNoMoreData];
        else [self.tableView.mj_footer endRefreshing];
        [self.dataArray  addObjectsFromArray:[ZJMineThroughRecordModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"list"]]];
           
        [self.tableView reloadData];
        }else{
            [LUtilityTools showAlertWithTitle:@"温馨提示" message:responseObject[@"msg"] buttonAction:nil];
            return;
        }
        [self.tableView.mj_header endRefreshing];

    }];
    
    
    
}

#pragma mark -- protocolCanleMoreViewDelegate
-(void)canleMoreView{
    [UIView animateWithDuration:0.2 animations:^{
        self.kwinDowView.alpha = 0;
        self.moreVoew.frame = CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

-(void)choosemoreView:(NSString *)jinStr goodsStr:(NSString *)goodsStr errorStr:(NSString *)errorStr{
    if ([jinStr containsString:@"进"]){
        [self.paramer addEntriesFromDictionary:@{@"direction":@"1"}];
    }else if ([jinStr containsString:@"出"]){
        [self.paramer addEntriesFromDictionary:@{@"direction":@"0"}];
    }
    
    if(goodsStr.length != 0){
        [self.paramer addEntriesFromDictionary:@{@"goodsTypeName":goodsStr}];
    }
    
    if ([errorStr containsString:@"正常"]) {
        [self.paramer addEntriesFromDictionary:@{@"status":@"1"}];
    }else if ([goodsStr containsString:@"异常"]){
        [self.paramer addEntriesFromDictionary:@{@"status":@"0"}];
    }
    
    [self loadNet];
    
}



- (void)setupUI {
    // 设置筛选视图
    [self setupFilterView];
    
    // 设置列表
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.filterView.frame), self.view.frame.size.width, self.view.frame.size.height - CGRectGetMaxY(self.filterView.frame)) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor backgroundGrayColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        pageNo = 1;
        [self.paramer addEntriesFromDictionary:@{@"pageNo":@(pageNo)}];
        [self loadNet];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        pageNo += 1;
        [self.paramer addEntriesFromDictionary:@{@"pageNo":@(pageNo)}];
        [self loadNet];
    }];
    
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.nodataView];
    [self.nodataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.filterView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    
    
}

- (void)setupFilterView {
    self.filterView = [[UIView alloc] initWithFrame:CGRectMake(0, StatusBarHeight, self.view.frame.size.width, 50)];
    self.filterView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.filterView];
    
    CGFloat btnWidth = self.view.frame.size.width / 4;
    
    // 开始时间按钮
    self.startTimeBtn = [self createFilterButtonWithTitle:@"开始时间" frame:CGRectMake(0, 0, btnWidth, 50)];
    [self.filterView addSubview:self.startTimeBtn];
    
    // 结束时间按钮
    self.endTimeBtn = [self createFilterButtonWithTitle:@"结束时间" frame:CGRectMake(btnWidth, 0, btnWidth, 50)];
    [self.filterView addSubview:self.endTimeBtn];
    
    // 类型按钮
    self.typeBtn = [self createFilterButtonWithTitle:@"选择进/出" frame:CGRectMake(btnWidth * 2, 0, btnWidth, 50)];
    [self.filterView addSubview:self.typeBtn];
    
    // 更多按钮
    self.moreBtn = [self createFilterButtonWithTitle:@"更多" frame:CGRectMake(btnWidth * 3, 0, btnWidth, 50)];
    [self.filterView addSubview:self.moreBtn];
}

- (UIButton *)createFilterButtonWithTitle:(NSString *)title frame:(CGRect)frame {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn addTarget:self action:@selector(filterButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

#pragma mark - Actions
- (void)filterButtonClicked:(UIButton *)sender {
    if (sender == self.moreBtn) {
        [UIView animateWithDuration:0.2 animations:^{
            self.kwinDowView.alpha = 0.3;
            self.moreVoew.frame = CGRectMake(100, 0, SCREEN_WIDTH - 100, SCREEN_HEIGHT);
        }];
        
    } else if (sender == self.startTimeBtn) {
        // 处理开始时间按钮点击
        __weak typeof(self)weakSelf = self;
        weakSelf.checkPickerView = [[SaTMNewUIPickerAlertView alloc]init];
        weakSelf.checkPickerView.block = ^(NSString * timeStr) {
            if (timeStr) {
                [self.startTimeBtn setTitle:timeStr forState:(UIControlStateNormal)];
                pageNo = 1;
                NSString *encodedTimeStr = [timeStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                [self.paramer addEntriesFromDictionary:@{@"checkTime[0]":encodedTimeStr}];
                [self loadNet];
            }
        };
        [kWindow addSubview:self.checkPickerView];
        
        
    } else if (sender == self.endTimeBtn) {
        // 处理结束时间按钮点击
        
        __weak typeof(self)weakSelf = self;
        weakSelf.checkPickerView = [[SaTMNewUIPickerAlertView alloc]init];
        weakSelf.checkPickerView.block = ^(NSString * timeStr) {
            if (timeStr) {
                [self.endTimeBtn setTitle:timeStr forState:(UIControlStateNormal)];
                pageNo = 1;
                NSString *encodedTimeStr = [timeStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                [self.paramer addEntriesFromDictionary:@{@"checkTime[1]":encodedTimeStr}];
                [self loadNet];
            }
        };
        [kWindow addSubview:self.checkPickerView];
        
        
    } else if (sender == self.typeBtn) {
        // 处理类型按钮点击
        
        __weak typeof (self)weakSelf = self;
        weakSelf.sexView = [SexAlertView new];
        weakSelf.sexView.dataSource = [NSMutableArray arrayWithObjects:@"全部",@"进",@"出", nil];
        weakSelf.sexView.block = ^(NSString * sexStr) {
            NSString * str;
            if([sexStr isEqualToString:@"进"]){
                str = @"1";
                [self.paramer addEntriesFromDictionary:@{@"direction":str}];
                [self.typeBtn setTitle:sexStr forState:(UIControlStateNormal)];
            }else if([sexStr isEqualToString:@"出"]){
                str = @"-1";
                [self.paramer addEntriesFromDictionary:@{@"direction":str}];
                [self.typeBtn setTitle:sexStr forState:(UIControlStateNormal)];
            }else{
                [self.paramer removeObjectForKey:@"direction"];
                [self.typeBtn setTitle:@"选择进/出" forState:(UIControlStateNormal)];
            }
            
            pageNo = 1;
            [self loadNet];
            
        };
        
        [kWindow addSubview:self.sexView];
        
        
        
    }
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"ThroughRecordCell";
    ZJMineThroughRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[ZJMineThroughRecordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    // 更新cell数据
    ZJMineThroughRecordModel *record = self.dataArray[indexPath.row];
    [cell updateWithRecord:record];
    
    return cell;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 110;
//}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    
    ZJMineThroughRecordModel * model = self.dataArray[indexPath.row];
    
    ZJMineThroughRecordInfoViewController * vc = [ZJMineThroughRecordInfoViewController new];
    if ([model.status boolValue] == YES) {
        vc.IsType = YES;
    }else{
        vc.IsType = NO;
    }
    vc.trafficId = model.id;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - ZJMineThroughRecordMoreDrawDelegate
- (void)moreDrawDidConfirmWithParams:(NSDictionary *)params {
    // 处理筛选参数，刷新列表
    NSLog(@"筛选参数: %@", params);
    // TODO: 根据筛选参数重新加载数据
    [self loadNet];
}

- (void)moreDrawDidCancel {
    // 用户取消筛选
    NSLog(@"用户取消筛选");
}



#pragma mark -- 懒加载
-(MineTrafficRecordListNetWorking *)manager{
    if (!_manager){
        _manager = [MineTrafficRecordListNetWorking new];
    }
    return _manager;
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array ];
    }
    return _dataArray;
}
-(NSMutableDictionary *)paramer{
    if (!_paramer){
        _paramer = [NSMutableDictionary dictionary];
    }
    return _paramer;
}

-(publicNodataView *)nodataView{
    if (!_nodataView) {
        _nodataView = [publicNodataView new];
        _nodataView.hidden = YES;
    }
    return _nodataView;
}

@end
